package com.tit.safetycontacts.view.dial;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Service;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tit.safetycontacts.R;
import com.tit.safetycontacts.TabMainActivity;
import com.tit.safetycontacts.application.MyApplication;
import com.tit.safetycontacts.bean.dial.CallLogBean;
import com.tit.safetycontacts.utils.ISVisible;
import com.tit.safetycontacts.view.adapter.dial.HomeDialAdapter;
import com.tit.safetycontacts.view.adapter.dial.T9Adapter;

/**
 * 这个是拨号界面的入口
 * 
 * @author Wangdong
 * 
 */
public class HomeDialActivity extends Activity implements OnClickListener {

	public AsyncQueryHandler asyncQuery;

	private HomeDialAdapter adapter;
	private ListView callLogList;

	private List<CallLogBean> list;

	public LinearLayout bohaopan;
	private LinearLayout keyboard_show_ll;
	private Button keyboard_show, keyboard_show_bottom;

	private Button phone_view;
	private Button delete;
	private Map<Integer, Integer> map = new HashMap<Integer, Integer>();
	private SoundPool spool;
	private AudioManager am = null;

	private MyApplication application;
	private ListView contact_list;
	private T9Adapter t9Adapter;

	/**
	 * wd
	 */

	String selection;
	private static final String TAG = "HomeDialActivity";
	static final String ACTION_CALLIN = "android.intent.action.PHONE_STATE";
	static final String ACTION_CALLOUT = "android.intent.action.NEW_OUTGOING_CALL";
	Uri uri_callLog;
	HomeDialActivity instance = null;
	public TabMainActivity tabMain;
	RelativeLayout rl_dial_page_popup = null;
	private LinearLayout ll_pop = null;
	private TextView topBar_title;
	private PopupWindow popupWindow;
	private LinearLayout layout_Pop;
	private ListView listView_Pop;
	private String pop_Title[] = { "通话记录", "呼入记录", "呼出记录", "未接记录" };

	private int x;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.home_dial_page);

		/*
		 * 监听电话的状态改变
		 */
		PhoneCallListener phoneListener = new PhoneCallListener();
		TelephonyManager telephonyManager = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		telephonyManager.listen(phoneListener,
				PhoneStateListener.LISTEN_CALL_STATE);

		/**
		 * 初始化数据
		 */
		selection = "1=1) group by(number";

		uri_callLog = CallLog.Calls.CONTENT_URI;// CallLog.Calls.CONTENT_URI
		instance = HomeDialActivity.this;
		rl_dial_page_popup = (RelativeLayout) findViewById(R.id.rl_dial_page_popup);
		topBar_title = (TextView) findViewById(R.id.topbar_title);
		ll_pop = (LinearLayout) findViewById(R.id.ll_pop);
		ll_pop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				topBar_title.getTop();

				showPopupWindow();

			}

		});

		// -----------------------------------------------
		/**
		 * 启动T9服务，监听一些控件,获取全局数据,
		 */
		application = (MyApplication) getApplication();
		Log.d("application", application + "");

		bohaopan = (LinearLayout) findViewById(R.id.bohaopan);
		keyboard_show_ll = (LinearLayout) findViewById(R.id.keyboard_show_ll);
		keyboard_show = (Button) findViewById(R.id.keyboard_show);
		keyboard_show_bottom = (Button) findViewById(R.id.keyboard_show_bottom);

		callLogList = (ListView) findViewById(R.id.call_log_list);
		contact_list = (ListView) findViewById(R.id.contact_list);
		asyncQuery = new MyAsyncQueryHandler(getContentResolver());

		keyboard_show.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				isDialPadAndTabHostShow();
			}
		});
		keyboard_show_bottom.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				isDialPadAndTabHostShow();

			}
		});
		/*
		 * 
		 * 加载按钮音符
		 */
		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		spool = new SoundPool(11, AudioManager.STREAM_SYSTEM, 5);
		map.put(0, spool.load(this, R.raw.dtmf0, 0));
		map.put(1, spool.load(this, R.raw.dtmf1, 0));
		map.put(2, spool.load(this, R.raw.dtmf2, 0));
		map.put(3, spool.load(this, R.raw.dtmf3, 0));
		map.put(4, spool.load(this, R.raw.dtmf4, 0));
		map.put(5, spool.load(this, R.raw.dtmf5, 0));
		map.put(6, spool.load(this, R.raw.dtmf6, 0));
		map.put(7, spool.load(this, R.raw.dtmf7, 0));
		map.put(8, spool.load(this, R.raw.dtmf8, 0));
		map.put(9, spool.load(this, R.raw.dtmf9, 0));
		map.put(11, spool.load(this, R.raw.dtmf11, 0));
		map.put(12, spool.load(this, R.raw.dtmf12, 0));
		/*
		 * 监听拨打电话按钮
		 */
		phone_view = (Button) findViewById(R.id.phone_view);
		phone_view.setOnClickListener(this);
		phone_view.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				if (null == application.getContactBeanList()
						|| application.getContactBeanList().size() < 1
						|| "".equals(s.toString())) {
					// 如果没有从application里获得数据，则显示callLogList,代表通话记录信息
					contact_list.setVisibility(View.INVISIBLE);
					callLogList.setVisibility(View.VISIBLE);
				} else {
					// 如果从application获得了数据
					if (null == t9Adapter) {
						// 从application里获得了数据，并且null == t9Adapter
						t9Adapter = new T9Adapter(HomeDialActivity.this);
						// 后台已经获得了所有联系人
						t9Adapter.assignment(application.getContactBeanList());
						// TextView tv = new TextView(HomeDialActivity.this);
						// tv.setBackgroundResource(R.drawable.dial_input_bg2);
						// listView.addFooterView(tv);
						contact_list.setAdapter(t9Adapter);
						contact_list.setTextFilterEnabled(true);
						contact_list
								.setOnScrollListener(new OnScrollListener() {
									public void onScrollStateChanged(
											AbsListView view, int scrollState) {

										// 滑动list的时候让拨号盘跟Tabhost不可见
										if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
											if (bohaopan.getVisibility() == View.VISIBLE) {
												bohaopan.setVisibility(View.GONE);
												ISVisible
														.tabHostInVisible(instance);
												keyboard_show_ll
														.setVisibility(View.VISIBLE);
											}
										}
									}

									public void onScroll(AbsListView view,
											int firstVisibleItem,
											int visibleItemCount,
											int totalItemCount) {
									}
								});
					} else {
						// 从application里获得了数据，并且null !=
						// t9Adapter,显示contact_list列表
						callLogList.setVisibility(View.INVISIBLE);
						contact_list.setVisibility(View.VISIBLE);
						contact_list
								.setOnScrollListener(new OnScrollListener() {
									public void onScrollStateChanged(
											AbsListView view, int scrollState) {
										if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
											if (bohaopan.getVisibility() == View.VISIBLE) {
												bohaopan.setVisibility(View.GONE);
												ISVisible
														.tabHostInVisible(instance);
												keyboard_show_ll
														.setVisibility(View.VISIBLE);
											}
										}
									}

									public void onScroll(AbsListView view,
											int firstVisibleItem,
											int visibleItemCount,
											int totalItemCount) {
									}
								});
						t9Adapter.getFilter().filter(s);
					}
				}

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
				// 让顶部的popupwindow下拉列表不可见
				if (contact_list.getVisibility() == View.VISIBLE) {
					rl_dial_page_popup.setVisibility(View.GONE);
				} else {
					rl_dial_page_popup.setVisibility(View.VISIBLE);
				}
			}
		});
		delete = (Button) findViewById(R.id.delete);
		delete.setOnClickListener(this);
		delete.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				phone_view.setText("");
				return false;
			}
		});

		for (int i = 0; i < 12; i++) {
			View v = findViewById(R.id.dialNum1 + i);
			v.setOnClickListener(this);
		}

		init();

	}

	// 异步查询通话记录中需要的数据
	public void init() {

		String sql = "SELECT max(date) as max_date, number, duration,type FROM calls WHERE (1=1) group by(number) ORDER BY date DESC";
		// String selection = "1=1) group by(number";

		String[] projection = { "MAX(date) AS date", CallLog.Calls.NUMBER,
				CallLog.Calls.TYPE, CallLog.Calls.CACHED_NAME,
				CallLog.Calls._ID }; // 查询的列
		asyncQuery.startQuery(0, null, uri_callLog, projection, selection,
				null, CallLog.Calls.DEFAULT_SORT_ORDER);

	}

	private class MyAsyncQueryHandler extends AsyncQueryHandler {

		public MyAsyncQueryHandler(ContentResolver cr) {
			super(cr);
		}

		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (cursor != null && cursor.getCount() > 0) {

				list = new ArrayList<CallLogBean>();
				SimpleDateFormat sfd = new SimpleDateFormat("MM-dd hh:mm");
				Date date;
				cursor.moveToFirst();
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);

					String number = cursor.getString(cursor
							.getColumnIndex(CallLog.Calls.NUMBER));

					date = new Date(cursor.getLong(cursor
							.getColumnIndex(CallLog.Calls.DATE)));

					int type = cursor.getInt(cursor
							.getColumnIndex(CallLog.Calls.TYPE));
					String cachedName = cursor.getString(cursor
							.getColumnIndex(CallLog.Calls.CACHED_NAME));// 缓存的名称与电话号码，如果它的存在
					int id = cursor.getInt(cursor
							.getColumnIndex(CallLog.Calls._ID));

					CallLogBean clb = new CallLogBean();
					clb.setId(id);
					clb.setNumber(number);
					clb.setName(cachedName);
					if (null == cachedName || "".equals(cachedName)) {
						clb.setName(number);
					}
					clb.setType(type);
					clb.setDate(sfd.format(date));

					list.add(clb);

				}
				if (list.size() > 0) {
					setAdapter(list);
				}
			}
		}

	}

	private void setAdapter(List<CallLogBean> list) {
		adapter = new HomeDialAdapter(this, list);
		// TextView tv = new TextView(this);
		// tv.setBackgroundResource(R.drawable.dial_input_bg2);
		// callLogList.addFooterView(tv);
		callLogList.setAdapter(adapter);
		callLogList.setOnScrollListener(new OnScrollListener() {

			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
					if (bohaopan.getVisibility() == View.VISIBLE) {
						bohaopan.setVisibility(View.GONE);
						ISVisible.tabHostInVisible(instance);
						keyboard_show_ll.setVisibility(View.VISIBLE);
					}
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
		callLogList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				System.out.println("点击了:" + position);

			}
		});
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.dialNum0:
			if (phone_view.getText().length() < 12) {
				play(0);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum1:
			if (phone_view.getText().length() < 12) {
				play(1);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum2:
			if (phone_view.getText().length() < 12) {
				play(2);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum3:
			if (phone_view.getText().length() < 12) {
				play(3);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum4:
			if (phone_view.getText().length() < 12) {
				play(4);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum5:
			if (phone_view.getText().length() < 12) {
				play(5);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum6:
			if (phone_view.getText().length() < 12) {
				play(6);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum7:
			if (phone_view.getText().length() < 12) {
				play(7);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum8:
			if (phone_view.getText().length() < 12) {
				play(8);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum9:
			if (phone_view.getText().length() < 12) {
				play(9);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialx:
			if (phone_view.getText().length() < 12) {
				play(11);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialj:
			if (phone_view.getText().length() < 12) {
				play(12);
				input(v.getTag().toString());
			}
			break;
		case R.id.delete:
			delete();
			break;
		case R.id.phone_view:
			if (phone_view.getText().toString().length() >= 4) {
				call(phone_view.getText().toString());
			}
			break;
		default:
			break;
		}
	}

	private void play(int id) {
		int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		int current = am.getStreamVolume(AudioManager.STREAM_MUSIC);

		float value = (float) 0.7 / max * current;
		spool.setVolume(spool.play(id, value, value, 0, 0, 1f), value, value);
	}

	private void input(String str) {
		String p = phone_view.getText().toString();
		phone_view.setText(p + str);
	}

	private void delete() {
		String p = phone_view.getText().toString();
		if (p.length() > 0) {
			phone_view.setText(p.substring(0, p.length() - 1));
		}
	}

	private void call(String phone) {
		Uri uri = Uri.parse("tel:" + phone);
		Intent it = new Intent(Intent.ACTION_CALL, uri);
		startActivity(it);
	}

	public void isDialPadAndTabHostShow() {
		if (bohaopan.getVisibility() == View.VISIBLE) {
			bohaopan.setVisibility(View.GONE);
			ISVisible.tabHostInVisible(instance);
			keyboard_show_ll.setVisibility(View.VISIBLE);
		} else {
			bohaopan.setVisibility(View.VISIBLE);
			ISVisible.tabHostVisible(instance);
			keyboard_show_ll.setVisibility(View.INVISIBLE);
		}
	}

	private void showPopupWindow() {
		x = getWindowManager().getDefaultDisplay().getWidth() / 6;
		layout_Pop = (LinearLayout) LayoutInflater.from(HomeDialActivity.this)
				.inflate(R.layout.top_pop_dialog, null);
		listView_Pop = (ListView) layout_Pop.findViewById(R.id.lv_dialog);
		listView_Pop.setAdapter(new ArrayAdapter<String>(HomeDialActivity.this,
				R.layout.top_pop_text, R.id.tv_pop_text, pop_Title));
		popupWindow = new PopupWindow(HomeDialActivity.this);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow
				.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 2 - 30);
		popupWindow.setHeight(265);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setContentView(layout_Pop);
		// showAsDropDown会把里面的view作为参照物，所以要那满屏幕parent
		// popupWindow.showAsDropDown(findViewById(R.id.tv_title), x, 10);
		// popupWindow.showAtLocation(findViewById(R.id.topbar_title),
		// Gravity.LEFT
		// | Gravity.TOP, x, y);//需要指定Gravity，默认情况是center.
		popupWindow.showAsDropDown(findViewById(R.id.topbar_title), 35 - x, 15);
		listView_Pop.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				topBar_title.setText(pop_Title[position]);
				popupWindow.dismiss();
				popupWindow = null;
				String[] projection_all = { CallLog.Calls.DATE,
						CallLog.Calls.NUMBER, CallLog.Calls.TYPE,
						CallLog.Calls.CACHED_NAME, CallLog.Calls._ID }; // 查询的列
				switch (position) {
				case 0:
					String selection_all = "1=1) group by(number";
					asyncQuery.startQuery(0, null, uri_callLog, projection_all,
							selection_all, null,
							CallLog.Calls.DEFAULT_SORT_ORDER);
					break;
				case 1:
					String selection_in = "type=1";
					asyncQuery.startQuery(0, null, uri_callLog, projection_all,
							selection_in, null,
							CallLog.Calls.DEFAULT_SORT_ORDER);
					break;
				case 2:
					String selection_out = "type=2";
					asyncQuery.startQuery(0, null, uri_callLog, projection_all,
							selection_out, null,
							CallLog.Calls.DEFAULT_SORT_ORDER);
					break;
				case 3:
					String selection_miss = "type=3";
					asyncQuery.startQuery(0, null, uri_callLog, projection_all,
							selection_miss, null,
							CallLog.Calls.DEFAULT_SORT_ORDER);
					break;

				default:
					break;
				}

			}

		});
	}

	@Override
	protected void onStart() {
		Log.d(TAG, "onStart");
		super.onStart();

	}

	@Override
	protected void onRestart() {
		Log.d(TAG, "onRestart");
		super.onRestart();

	}

	@Override
	protected void onResume() {
		Log.d(TAG, "onResume");

		String[] projection = { "MAX(date) AS date", CallLog.Calls.NUMBER,
				CallLog.Calls.TYPE, CallLog.Calls.CACHED_NAME,
				CallLog.Calls._ID }; // 查询的列
		asyncQuery.startQuery(0, null, uri_callLog, projection, selection,
				null, CallLog.Calls.DEFAULT_SORT_ORDER);
		super.onResume();

	}

	@Override
	protected void onPause() {
		Log.d(TAG, "onPause");
		super.onPause();
	}

	@Override
	protected void onStop() {
		Log.d(TAG, "onStop");
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		Log.d(TAG, "onDestroy");
		super.onDestroy();
	}

	/**
	 * 监听电话的状态，当挂断的时候从系统的通讯录界面跳回自己的Activity
	 * 
	 * @author Wangdong
	 * 
	 */
	private class PhoneCallListener extends PhoneStateListener {
		private boolean isPhoneCalling = false;

		String LOG_TAG = "LOGGING 123";

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// 当处于拨号状态中..还是响铃
			if (TelephonyManager.CALL_STATE_RINGING == state) {
				Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);

			}
			// 当处于通话中
			if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
				Log.i(LOG_TAG, "OFFHOOK");
				isPhoneCalling = true;
			}
			// 当处于待机状态中
			// run when class initial and phone call ended,
			// need detect flag from CALL_STATE_OFFHOOK
			if (TelephonyManager.CALL_STATE_IDLE == state) {

				Log.i(LOG_TAG, "IDLE");

				if (isPhoneCalling) {

					Log.i(LOG_TAG, "restart app");

					// restart app
					Intent i = getBaseContext().getPackageManager()
							.getLaunchIntentForPackage(
									getBaseContext().getPackageName());
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					// i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					startActivity(i);
					isPhoneCalling = false;
				}

			}
		}
	}

}
